const puppeteer = require("puppeteer");
const fs = require("fs");
const { SINGER_LIST, INIT_INDEX, ROOT_DIR } = require("./assets/config");
const { getMusicDownloadUrlList } = require("./modules/music");

/**
 *
 * @param {*} name
 * @param {*} index
 * @returns
 */
const startCrawler = async (name = "", index = 0) => {
  const singerName = process.argv[2] || name;

  const isExist = fs.existsSync(`${ROOT_DIR}/${singerName}`);

  !isExist && fs.mkdirSync(`${ROOT_DIR}/${singerName}`);
  const browser = await puppeteer.launch({
    headless: false,
    args: ["--start-maximized"],
  });
  browser.on("disconnected", () => {
    console.log("disconnected ------------");
  });
  const page = await browser.newPage();
  await page.setViewport({ width: 1440, height: 750 });
  await page.setDefaultTimeout(30000);
  if (singerName) {
    const singer = SINGER_LIST.find((singer) => singer.name === singerName);
    await page.goto(singer?.url, { waitUntil: "domcontentloaded" });
    console.log('----- page loaded success ----')
    await getMusicDownloadUrlList(browser, page, INIT_INDEX, singer?.url, singerName);
    return;
  }
  console.log("====== not fund singer ====");
  await page.goto(SINGER_LIST[index]?.url);
  await getMusicDownloadUrlList(browser, page, INIT_INDEX, SINGER_LIST[index]?.url, singerName);
};

void startCrawler();
